using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Lzfy_Refund_Service.Models;
using Lzfy_Refund_Service.Services;
using System.ComponentModel.DataAnnotations;

namespace Lzfy_Refund_Service.Controllers
{
    /// <summary>
    /// 密码更新任务控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    [Authorize]
    public class PasswordUpdateTaskController : ControllerBase
    {
        private readonly IPasswordUpdateTaskService _taskService;
        private readonly ILogger<PasswordUpdateTaskController> _logger;

        public PasswordUpdateTaskController(
            IPasswordUpdateTaskService taskService,
            ILogger<PasswordUpdateTaskController> logger)
        {
            _taskService = taskService;
            _logger = logger;
        }

        /// <summary>
        /// 创建密码更新任务
        /// </summary>
        /// <param name="request">创建任务请求</param>
        /// <returns>创建任务响应</returns>
        [HttpPost("create")]
        public async Task<ActionResult<CreatePasswordUpdateTaskResponse>> CreateTask([FromBody] CreatePasswordUpdateTaskRequest request)
        {
            try
            {
                if (request == null)
                {
                    return BadRequest(new CreatePasswordUpdateTaskResponse
                    {
                        Success = false,
                        Message = "请求体不能为空"
                    });
                }

                if (!ModelState.IsValid)
                {
                    var errors = ModelState.Values
                        .SelectMany(v => v.Errors)
                        .Select(e => e.ErrorMessage)
                        .ToList();
                    
                    return BadRequest(new CreatePasswordUpdateTaskResponse
                    {
                        Success = false,
                        Message = $"请求参数验证失败: {string.Join(", ", errors)}"
                    });
                }

                var response = await _taskService.CreateTaskAsync(request);
                
                if (response.Success)
                {
                    _logger.LogInformation("创建密码更新任务成功，任务ID: {TaskId}, 患者ID: {PatientId}", 
                        response.TaskId, request.PatientId);
                    return Ok(response);
                }
                else
                {
                    _logger.LogWarning("创建密码更新任务失败，患者ID: {PatientId}, 错误: {Error}", 
                        request.PatientId, response.Message);
                    return BadRequest(response);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建密码更新任务时发生异常，患者ID: {PatientId}", request?.PatientId);
                return StatusCode(500, new CreatePasswordUpdateTaskResponse
                {
                    Success = false,
                    Message = "服务器内部错误"
                });
            }
        }

        /// <summary>
        /// 查询任务状态
        /// </summary>
        /// <param name="taskId">任务ID</param>
        /// <returns>任务状态响应</returns>
        [HttpGet("status/{taskId}")]
        public async Task<ActionResult<QueryTaskStatusResponse>> QueryTaskStatus([Required] string taskId)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(taskId))
                {
                    return BadRequest(new QueryTaskStatusResponse
                    {
                        Success = false,
                        Message = "任务ID不能为空"
                    });
                }

                var request = new QueryTaskStatusRequest { TaskId = taskId };
                var response = await _taskService.QueryTaskStatusAsync(request);
                
                if (response.Success)
                {
                    return Ok(response);
                }
                else
                {
                    return NotFound(response);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询任务状态时发生异常，任务ID: {TaskId}", taskId);
                return StatusCode(500, new QueryTaskStatusResponse
                {
                    Success = false,
                    Message = "服务器内部错误"
                });
            }
        }

        /// <summary>
        /// 取消任务
        /// </summary>
        /// <param name="taskId">任务ID</param>
        /// <returns>取消任务响应</returns>
        [HttpPost("cancel/{taskId}")]
        public async Task<ActionResult<CancelTaskResponse>> CancelTask([Required] string taskId)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(taskId))
                {
                    return BadRequest(new CancelTaskResponse
                    {
                        Success = false,
                        Message = "任务ID不能为空"
                    });
                }

                var request = new CancelTaskRequest { TaskId = taskId };
                var response = await _taskService.CancelTaskAsync(request);
                
                if (response.Success)
                {
                    _logger.LogInformation("取消任务成功，任务ID: {TaskId}", taskId);
                    return Ok(response);
                }
                else
                {
                    _logger.LogWarning("取消任务失败，任务ID: {TaskId}, 错误: {Error}", taskId, response.Message);
                    return BadRequest(response);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "取消任务时发生异常，任务ID: {TaskId}", taskId);
                return StatusCode(500, new CancelTaskResponse
                {
                    Success = false,
                    Message = "服务器内部错误"
                });
            }
        }

        /// <summary>
        /// 获取患者的待执行任务
        /// </summary>
        /// <param name="patientId">患者ID</param>
        /// <returns>待执行任务列表</returns>
        [HttpGet("pending/{patientId}")]
        public async Task<ActionResult<List<PasswordUpdateTask>>> GetPendingTasks([Required] string patientId)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(patientId))
                {
                    return BadRequest("患者ID不能为空");
                }

                var tasks = await _taskService.GetPendingTasksByPatientIdAsync(patientId);
                return Ok(tasks);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取患者待执行任务时发生异常，患者ID: {PatientId}", patientId);
                return StatusCode(500, "服务器内部错误");
            }
        }

        /// <summary>
        /// 获取任务统计信息
        /// </summary>
        /// <returns>任务统计信息</returns>
        [HttpGet("statistics")]
        [Authorize(Roles = "Admin,Manager")]
        public async Task<ActionResult<Dictionary<string, int>>> GetTaskStatistics()
        {
            try
            {
                var statistics = await _taskService.GetTaskStatisticsAsync();
                return Ok(statistics);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取任务统计信息时发生异常");
                return StatusCode(500, "服务器内部错误");
            }
        }
    }
}